package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Travel;
import cn.wolfcode.trip.base.domain.TravelContent;
import cn.wolfcode.trip.base.mapper.TravelContentMapper;
import cn.wolfcode.trip.base.mapper.TravelMapper;
import cn.wolfcode.trip.base.query.TravelQueryObject;
import cn.wolfcode.trip.base.service.ITravelService;
import cn.wolfcode.trip.base.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class TravelServiceImpl implements ITravelService {

    @Autowired
    private TravelMapper travelMapper;

    @Autowired
    private TravelContentMapper travelContentMapper;

    @Override
    public PageInfo query(TravelQueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize(), true, false, null);
        List<Travel> list = travelMapper.selectForList(qo);
        return new PageInfo(list);
    }

    @Override
    public void saveOrUpdate(Travel travel) {
        if (travel.getId() != null) {
            travel.setLastUpdateTime(new Date());
            travelMapper.updateByPrimaryKey(travel);

            travel.getTravelContent().setId(travel.getId());
            travelContentMapper.updateByPrimaryKey(travel.getTravelContent());
        } else {
            // 设置作者
            travel.setAuthor(UserContext.getCurrentUser());
            // 设置创建时间
            travel.setCreateTime(new Date());
            // 设置更新时间
            travel.setLastUpdateTime(new Date());
            // 保存游记信息
            travelMapper.insert(travel);
            // 保存游记内容
            travel.getTravelContent().setId(travel.getId());
            travelContentMapper.insert(travel.getTravelContent());
        }
    }

    @Override
    public Travel getById(Long id) {
        return travelMapper.selectByPrimaryKey(id);
    }

    @Override
    public TravelContent getContentById(Long id) {
        return travelContentMapper.selectByPrimaryKey(id);
    }

    @Override
    public void updateState(Travel travel) {
        // 如果是发布状态设置发布时间
        if (travel.getState() == Travel.STATE_RELEASE) {
            travel.setReleaseTime(new Date());
        }
        travelMapper.updateState(travel);
    }
}
